if (!window.Scribd) var Scribd = new Object();
if (!Scribd.Ads) Scribd.Ads = new Object();

if (!Scribd.Ads.use_gpt) Scribd.Ads.use_gpt = false;
Scribd.Ads.attributes = {};
Scribd.Ads.max_between_page = 21;

Scribd.Ads.addAttribute = function(name, value) {
  // assert(value != undefined);
  if (Scribd.Ads.attributes[name] == undefined && value != undefined) {
    if (!Scribd.Ads.use_gpt) {
      GA_googleAddAttr(name, value);
    }
    Scribd.Ads.attributes[name] = value;
  }
};

Scribd.Ads.ActivateOnView = function(nodes, on_view, get_offset_for_node) {
  this.nodes = nodes;

  this.get_offset_for_node = get_offset_for_node || function(id) {
    var node = $(id);
    return node.viewportOffset()[1];
  }

  // call me when the viewport has changed
  this.on_update = function() {
    if (this.nodes.length == 0) return;
    var _this = this;
    var scroll = document.viewport.getScrollOffsets();
    var max_y = scroll[1] + document.viewport.getHeight();

    var to_remove = [];
    this.nodes.each(function(node) {
      if (_this.get_offset_for_node(node) < max_y) {
        on_view(node);
        to_remove.push(node);
      }
    });

    if (to_remove.length > 0) {
      var ri = 0;
      this.nodes = this.nodes.select(function(node) {
        if (node == to_remove[ri]) {
          ri++;
          return false;
        }
        return true;
      });
    }
  }

  this.add_node = function(node_name) {
    this.nodes.push(node_name);
    this.on_update();
  }

  this.register = function() {
    var bound = this.on_update.bind(this);
    Event.observe(document, "dom:loaded", bound);
    Event.observe(window, "scroll", bound);
    Event.observe(window, "resize", bound);
    return this;
  }
};

(function() {
  var defined_slots = {};
  var view_listener = new Scribd.Ads.ActivateOnView([], function(unit_name) {
    googletag.display(defined_slots[unit_name]);
  }, function (unit_name) {
    var node = $(defined_slots[unit_name])
    return node.viewportOffset()[1];
  }).register();

  // gpt only
  Scribd.Ads.defineSlot = function(unit_name, size, node_id) {
    var full_name = '/1024966/ca-pub-7291399211842501/' + unit_name;
    googletag.defineSlot(full_name, size, node_id).addService(googletag.pubads());
    defined_slots[unit_name] = node_id;
  };

  Scribd.Ads.addUnit = function(unit_name, wait_to_be_seen) {
    if (Scribd.Ads.use_gpt) {
      googletag.cmd.push(function() {
        var tag_id = defined_slots[unit_name];
        if (!tag_id) {
          throw new 'Attempting to display undeclared ad unit: ' + unit_name;
        }
        if (wait_to_be_seen) {
          view_listener.add_node(unit_name);
        } else {
          googletag.display(tag_id);
        }
      });
    } else {
      GA_googleAddSlot("ca-pub-7291399211842501", unit_name);
      document.write('<div class="hideable_ad" id="' + unit_name + '_container">');
      GA_googleFillSlot(unit_name);
      document.write('</div>');
    }
  };
})();

Scribd.Ads.betweenUnitForPage = function(page_num) {
  var name;
  if (page_num == 1)
    return ['Doc_Between_Top_FullBanner_468x60', [468, 60]];
  else if (page_num % 2 == 1 && page_num <= 21)
    return ['Doc_Between_Leaderboard_BTF_728x90_' + page_num, [728, 90]];
}

Scribd.Ads.addBetweenPageUnit = function(page_num) {
  if (Scribd.Ads.attributes['UserState'] == 'In')
    return;

  if (navigator.userAgent.match(/iPad/i))
    return;

  var unit = Scribd.Ads.betweenUnitForPage(page_num);
  if (!unit) return;
  var name = unit[0];
  Scribd.Ads.addUnit(name, true);
};

Scribd.Ads.addFullPageUnit = function(image_url, link_url) {
  document.write('<div class="autogen_class_views_shared_ad_code">'); // hack so we can get Erector styles but call the js in genserve or DFP
  document.write('<div class="full_page_ad_container">');
  document.write('<div class="full_page_ad">');
  document.write('<a href="' + link_url + '"><img src="' + image_url + '" border="0"></a>');
  document.write('</div>');
  document.write('<div class="b_tl"></div><div class="b_tr"></div><div class="b_br"></div><div class="b_bl"></div><div class="b_t"></div><div class="b_r"></div><div class="b_b"></div><div class="b_l"></div>');
  document.write('</div>');
  document.write('</div>');

  Scribd.Ads.originalFullPageAdWidth = $$('.full_page_ad')[0].getWidth();
  Scribd.Ads.originalFullPageAdInnerWidth = $$('.full_page_ad')[0].down('a').getWidth();

  Scribd.Ads.enableResizingFullPageAds();
};

Scribd.Ads.enableResizingFullPageAds = function() {
  if (typeof docManager === 'undefined') {
    setTimeout(Scribd.Ads.enableResizingFullPageAds, 100);
    return;
  };

  docManager.addEvent('zoomed', Scribd.Ads.resizeFullPageAds);
  docManager.addEvent('enteredFullscreen', Scribd.Ads.resizeFullPageAds);
  docManager.addEvent('exitedFullscreen', Scribd.Ads.resizeFullPageAds);
};

Scribd.Ads.resizeFullPageAds = function() {
  $$('.full_page_ad').each(function(ad) {
    var page = Scribd.Ads.makeFakePageForZooming(ad);
    page.setWidth(docManager._pageWidths);

    if (ad.getWidth() > Scribd.Ads.originalFullPageAdWidth) {
      ad.style.marginLeft = '0px';
      if (ad.style.WebkitTransformOrigin)
        ad.style.WebkitTransformOrigin = 'top center';
      else if (ad.style.MozTransformOrigin)
        ad.style.MozTransformOrigin = 'top center';
      else if (ad.style.OTransformOrigin)
        ad.style.OTransformOrigin = 'top center';
      // TODO: add an else clause that makes this work right in IE
    } else {
      ad.style.marginLeft = ad.getWidth() * (0.5 - ad.down('a').getWidth() / (2 * Scribd.Ads.originalFullPageAdWidth)) + 'px';
      if (ad.style.WebkitTransformOrigin)
        ad.style.WebkitTransformOrigin = 'top left';
      else if (ad.style.MozTransformOrigin)
        ad.style.MozTransformOrigin = 'top left';
      else if (ad.style.OTransformOrigin)
        ad.style.OTransformOrigin = 'top left';
      else
        ad.style.marginLeft = (Scribd.Ads.originalFullPageAdWidth - Scribd.Ads.originalFullPageAdInnerWidth) / 2 + 'px';
    }
  });
};

Scribd.Ads.makeFakePageForZooming = function(ad) {
  if (!Scribd.Ads.fakePagesForZooming)
    Scribd.Ads.fakePagesForZooming = {};

  if (Scribd.Ads.fakePagesForZooming[ad])
    return Scribd.Ads.fakePagesForZooming[ad];

  var fake_page = function() {};

  fake_page.innerPageElem = ad;
  fake_page.containerElem = ad.parentNode;
  fake_page.origWidth = ad.parentNode.getWidth();
  fake_page.origHeight = ad.parentNode.getHeight();
  fake_page._innerPageVisible = true;

  fake_page._setZoomScale = docManager.pages[1]._setZoomScale;
  fake_page._fitContentsToWidth = docManager.pages[1]._fitContentsToWidth;
  fake_page.setWidth = docManager.pages[1].setWidth;

  Scribd.Ads.fakePagesForZooming[ad] = fake_page;
  return fake_page;
};

Scribd.Ads.addRefreshUnit = function(name) {
  var attributes = $H(Scribd.Ads.attributes).map(function(pair) {
    return escape(pair.key) + '=' + escape(pair.value);
  }).join('&');
  var url_params = 'ad_unit=' + escape(name) + '&url=' + escape(window.location.href) + '&attributes=' + escape(attributes);
  var size = name.match(/.*_(\d+)x(\d+)$/);
  document.write('<div id="' + name + '_container" class="hideable_ad"></div>');
  Scribd.Ads.refreshIframe($(name + '_container'), size[1], size[2], url_params, 0);
  Scribd.Ads.observeUserActivity();
};

Scribd.Ads.refreshIframe = function(container, width, height, url_params, skip) {
  if (Scribd.Ads.userIsActive || !Scribd.Ads.trackEngagement) {
    if (container.hasChildNodes())
      container.childNodes[0].remove();

    var iframe = document.createElement('iframe');
    iframe.width = width;
    iframe.height = height;
    iframe.scrolling = 'no';
    iframe.frameBorder = 0;
    iframe.marginWidth = 0;
    iframe.marginHeight = 0;
    iframe.allowTransparency = true;
    iframe.src = Scribd.cdn_path + 'ad_refresher.html#' + url_params + '&skip=' + skip;
    container.appendChild(iframe);
  }

  setTimeout(function() { Scribd.Ads.refreshIframe(container, width, height, url_params, skip + 1); }, Scribd.Ads.refreshInterval * 1000);
};

var get_server_option = function(name, default_value) {
  if (typeof Scribd.ServerOptions == 'undefined' || eval('typeof Scribd.ServerOptions.' + name) == 'undefined')
    return default_value;

  return eval('Scribd.ServerOptions.' + name);
};

Scribd.Ads.trackEngagement = false;
Scribd.Ads.userIsActive = false;
Scribd.Ads.inactivityTimer = null;
Scribd.Ads.idleTimeBeforeInactive = get_server_option('ad_refresh_idle_time_before_inactive', 60);
Scribd.Ads.refreshInterval = get_server_option('ad_refresh_interval', 60);
Scribd.Ads.delayBeforeTrackingEngagement = get_server_option('ad_refresh_engagement_tracking_delay', 0);

setTimeout(function() {
  Scribd.Ads.trackEngagement = true;
}, Scribd.Ads.delayBeforeTrackingEngagement * 1000);

Scribd.Ads.onUserActivity = function() {
  Scribd.Ads.userIsActive = true;
  clearTimeout(Scribd.Ads.inactivityTimer);
  Scribd.Ads.inactivityTimer = setTimeout(Scribd.Ads.onUserInactivity, Scribd.Ads.idleTimeBeforeInactive * 1000);
};

Scribd.Ads.onUserInactivity = function() {
  Scribd.Ads.userIsActive = false;
};

Scribd.Ads.observingUserActivity = false;

Scribd.Ads.observeUserActivity = function() {
  if (!Scribd.Ads.observingUserActivity) {
    Scribd.Ads.onUserActivity(); // we consider them active to start off
    document.observe('mousemove', Scribd.Ads.onUserActivity);
    Event.observe(window, 'scroll', Scribd.Ads.onUserActivity);
    Scribd.Ads.observingUserActivity = true;
  }
}

Scribd.Ads.onViewModeChange = function(new_mode, old_mode) {
  if (old_mode == 'scroll')
    $$('.between_page_ads').each(function(ad) { ad.hide(); });
  if (new_mode == 'scroll')
    $$('.between_page_ads').each(function(ad) { ad.show(); });
};

if (typeof docManager !== 'undefined') {
    docManager.addEvent('viewmodeChanged', Scribd.Ads.onViewModeChange);
}
